//
// Created by mio on 25-5-19.
//

#include "AudioRender.h"
#include <QMediaDevices>

static QAudioFormat::SampleFormat bitsToSampleFormat(int bits)
{
    switch (bits) {
        case  8:  return QAudioFormat::UInt8;
        case 16:  return QAudioFormat::Int16;
        case 32:  return QAudioFormat::Int32;  // 如果解码得到浮点，可改成 Float
        default:  return QAudioFormat::Unknown;
    }
}

AudioRender::AudioRender()
{

}

AudioRender::~AudioRender()
{

}

int AudioRender::AvailableBytes()
{
    return audioSink_ ? static_cast<int>(audioSink_->bytesFree()) : -1;
}

bool AudioRender::InitAudio(int nChannels, int SampleRate, int nSampleSizeBits)
{
    if (audioSink_ || is_initail_)
        return true;

    sampleBits_ = nSampleSizeBits;

    // ---- 填写 QAudioFormat ----
    audioFmt_.setChannelCount(nChannels);
    audioFmt_.setSampleRate(SampleRate);
    audioFmt_.setSampleFormat(bitsToSampleFormat(sampleBits_));

    // （可选）检查当前输出设备是否支持此格式
    QAudioDevice defaultDev = QMediaDevices::defaultAudioOutput();
    if (!defaultDev.isFormatSupported(audioFmt_)) {
        qWarning("Raw audio format not supported by backend.");
        return false;
    }

    // ---- 创建 QAudioSink ----
    audioSink_ = new QAudioSink(defaultDev, audioFmt_);
    audioSink_->setBufferSize(409600);
    audioSink_->setVolume(volume_ / 100.0);   // Qt6: volume 是 0.0–1.0

    device_ = audioSink_->start();
    if (!device_)
        return false;

    is_initail_ = true;
    return true;
}

void AudioRender::Write(AVFramePtr frame)
{
    if (!device_ || !audioSink_ || sampleBits_ == -1)
        return;

    const int bytesPerSample = sampleBits_ / 8;
    const int dataBytes = frame->nb_samples * frame->channels * bytesPerSample;

    QByteArray audioData(reinterpret_cast<char*>(frame->data[0]), dataBytes);
    device_->write(audioData);

    av_frame_unref(frame.get());
}


